﻿using Company.Config;
using Company.Hardware.Acs;
using Company.Logger.Logs;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace Company.Main.ViewModels
{
    public class TerminalCommandViewModel : BindableBase
    {
        public ObservableCollection<Log> LogList { get;private set; }
        public AcsControllerProvider AcsControllerProvider { get;private set; }
        private string _SendContent;

        public string SendContent
        {
            get { return _SendContent; }
            set { _SendContent = value; RaisePropertyChanged(); }
        }
        public DelegateCommand<object> SendTerminalCommand { get;}
        public DelegateCommand ClearLogsCommand { get;}
        public TerminalCommandViewModel(AcsControllerProvider acsControllerProvider, Logger.Logs.Logger logger)
        {
            AcsControllerProvider = acsControllerProvider;
            LogList = logger.Logs;
            logger.Logs.CollectionChanged += (sender,e) => 
            {
                // 获取当天日期作为文件名
                //string date = DateTime.Now.ToString("yyyy-MM-dd");
                //string filePath = $"{date}.txt";
                //logger.SaveToFile(ProfilePaths.LogFilePath+ filePath);
            };
            SendTerminalCommand = new DelegateCommand<object>(SendTerminal);
            ClearLogsCommand = new DelegateCommand(ClearLogs);
            AcsControllerProvider.AcsController.AcsExceptionEvent += (ex) => 
            {
                // ObservableCollection类型不支持事件线程调度
                Application.Current.Dispatcher.Invoke(() => 
                {
                    if (LogList.Count > 2000) LogList.Clear();
                    var log = new Log(1, DateTime.Now, ex.ToString(), LogLevel.Error);
                    LogList.Add(log);
                });
            };
        }
        /// <summary>
        /// 清除Logs
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void ClearLogs()
        {
            LogList.Clear();
        }

        /// <summary>
        /// 发送终端指令
        /// </summary>
        /// <param name="obj"></param>
        private void SendTerminal(object obj)
        {
            if (LogList.Count > 1000) LogList.Clear();
            string command = obj as string;
            if (string.IsNullOrEmpty(command))
            {
                var log = new Log(1, DateTime.Now, "send command is empty or null", LogLevel.Warning);
                LogList.Add(log);
                return;
            }
            var result = AcsControllerProvider.AcsController.SendCommand(command);
            var newLog = new Log(1, DateTime.Now, result, LogLevel.Info);
            LogList.Add(newLog);
        }
    }
}
